package com.suxin.chain;

import com.suxin.chain.Interceptor.Interceptor;
import com.suxin.chain.domain.ContractRequest;
import com.suxin.chain.domain.ContractResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author: tang
 * @Description:
 * @Date 2024/6/20 10:26
 */
@Slf4j
public class ContractChain<T extends ContractRequest> implements Chain<T, ContractResponse>{

    private final Integer index;
    private final List<Interceptor<T, ContractResponse>> interceptors;

    private final T request;

    public ContractChain(Integer index, List<Interceptor<T, ContractResponse>> interceptors, T request) {
        this.index = index;
        this.interceptors = interceptors;
        this.request = request;
    }

    @Override
    public T request() {
        return request;
    }

    @Override
    public ContractResponse proceed(T request) {
        if (index > interceptors.size()) {
            return new ContractResponse();
        }
        Interceptor<T, ContractResponse> interceptor = interceptors.get(index);

        Class<? extends Interceptor> aClass = interceptor.getClass();

        log.info("当前节点：{}",aClass.getSimpleName());

        // 下一个链
        ContractChain<T> chain = new ContractChain<>(index + 1, interceptors, request());
        return interceptor.interceptor(chain);
    }
}
